Flutter Widget Router

Manages opening and closing pages in an application.

Key Components:

Demo

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      routerDelegate: CustomRouterDelegate(),
      routeInformationParser: CustomRouteInformationParser(),
    );
  }
}

Information Parser:

class CustomRouteInformationParser 
	extends RouteInformationParser<String> {
  @override
  Future<String> parseRouteInformation(
	  RouteInformation routeInformation) async {
    // You can customize the parsing logic here.
    // For now, we'll just use the route location directly.
    return routeInformation.location ?? '/';
  }

  @override
  RouteInformation restoreRouteInformation(String path) {
    return RouteInformation(location: path);
  }
}

Router Delegate:

class CustomRouterDelegate extends RouterDelegate<String>
    with ChangeNotifier, 
         PopNavigatorRouterDelegateMixin<String> {
  String _currentPath = '/';

  @override
  GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

  @override
  String get currentConfiguration => _currentPath;

  @override
  Future<void> setNewRoutePath(String path) async {
    _currentPath = path;
    notifyListeners();
  }

  @override
  Widget build(BuildContext context) {
    return Navigator(
      key: navigatorKey,
      pages: [
        MaterialPage(
	        child: HomePage(), 
	        key: ValueKey('Home')),
        if (_currentPath == '/details') 
	        MaterialPage(
		        child: DetailsPage(), 
		        key: ValueKey('Details')),
      ],
      onPopPage: (route, result) {
        if (!route.didPop(result)) return false;
        // Update the current path when a route is popped
        _currentPath = '/';
        notifyListeners();
        return true;
      },
    );
  }
}

In this demo, CustomRouteInformationParser parses the route information into a String. The CustomRouterDelegate then uses this string to determine which page to display. The HomePage includes a button to navigate to the DetailsPage, and the Navigator in the RouterDelegate is used to manage the stack of pages.

This is a basic example. In a real-world application, you would likely have more complex route parsing and handling logic.

Architectural Design

An application can have zero, one, or many Router widgets, depending on its needs.

No Router:

Multiple Routers:

State Restoration

Capable of restoring the current configuration after app restarts.


本文作者:Maeiee

本文链接:Flutter Widget Router

版权声明:如无特别声明,本文即为原创文章,版权归 Maeiee 所有,未经允许不得转载!


喜欢我文章的朋友请随缘打赏,鼓励我创作更多更好的作品!